/**
 * 用户详情对话框（可用于添加和修改对话框）
 */
var UserInfoDlg = {
    userInfoData: {},
    zTreeInstance : null
};

/**
 * 清除数据
 */
UserInfoDlg.clearData = function () {
    this.userInfoData = {};
};

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
UserInfoDlg.set = function (key, val) {
    this.userInfoData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    return this;
};

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
UserInfoDlg.get = function (key) {
    return $("#" + key).val();
};

/**
 * 关闭此对话框
 */
UserInfoDlg.close = function () {
    parent.layer.close(window.parent.MgrUser.layerIndex);
};

/**
 * 点击部门input框时
 *
 * @param e
 * @param treeId
 * @param treeNode
 * @returns
 */
UserInfoDlg.onClickDept = function (e, treeId, treeNode) {
    $("#citySel").attr("value", instance.getSelectedVal());
    $("#deptId").attr("value", treeNode.id);
    console.log($("#deptId").val());
};

/**
 * 显示部门选择的树
 *
 * @returns
 */
UserInfoDlg.showDeptSelectTree = function () {
    var cityObj = $("#citySel");
    var cityOffset = $("#citySel").offset();
    $("#menuContent").css({
        left: cityOffset.left + "px",
        top: cityOffset.top + cityObj.outerHeight() + "px"
    }).slideDown("fast");

    $("body").bind("mousedown", onBodyDown);
};

/**
 * 显示用户详情部门选择的树
 *
 * @returns
 */
UserInfoDlg.showInfoDeptSelectTree = function () {
    var cityObj = $("#citySel");
    var cityPosition = $("#citySel").position();
    $("#menuContent").css({
        left: cityPosition.left + "px",
        top: cityPosition.top + cityObj.outerHeight() + "px"
    }).slideDown("fast");

    $("body").bind("mousedown", onBodyDown);
};

/**
 * 隐藏部门选择的树
 */
UserInfoDlg.hideDeptSelectTree = function () {
    $("#menuContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);// mousedown当鼠标按下就可以触发，不用弹起
};

/**
 * 收集数据
 */
UserInfoDlg.collectData = function () {
    this.set('id').set('userName').set('sex').set('password').set('avatar')
        .set('email').set('name').set('birthday').set('officeId').set('phone').set('roleId');
};

/**
 * 验证数据非空
 */
UserInfoDlg.provingNull = function () {
    if(this.get('userName') && this.get('name') && 
    		this.get('sex') && this.get('birthday') && 
    		this.get('password') && this.get('parentName') &&
    		this.get('email') && this.get('phone') && this.get('roleId')){  	
    	return true;
    } else {
    	return false;
    }
};

/**
 * 验证邮箱及手机号数据
 */
UserInfoDlg.provingData = function () {
	var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
    if (reg.test(this.get('email')) && (/^1[3|4|5|7|8]\d{9}$/.test(this.get('phone')))) {
    	return true;
    } else {
    	return false;
    }
};

/**
 * 验证两个密码是否一致
 */
UserInfoDlg.validatePwd = function () {
    var password = this.get("password");
    var rePassword = this.get("rePassword");
    if (password == rePassword) {
        return true;
    } else {
        return false;
    }
};

/**
 * 提交添加用户
 */
UserInfoDlg.addSubmit = function () {
    this.clearData();
    this.collectData();
    
    if (!this.provingNull()) {
        Feng.error("请确认必填项");
        return;
    }
    if (!this.provingData()) {
        Feng.error("邮箱格式或手机号不正确,请重新填写");
        return;
    }
    if ($.trim(this.get('password')).length < 6){
    	Feng.error("密码长度必须大于6位数");
        return;
    }
    if (!this.validatePwd()) {
        Feng.error("两次密码输入不一致");
        return;
    }
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/sys/sysUser/save/add", function (data) {
        if(data.resultCode==0){
        	Feng.success("添加成功!");
            window.parent.MgrUser.table.refresh();
            UserInfoDlg.close();
    	}else{
    		Feng.error(data.msg + "!");
    	}
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.userInfoData);
    ajax.start();
};

/**
 * 提交修改
 */
UserInfoDlg.editSubmit = function () {

    this.clearData();
    this.collectData();
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/sys/sysUser/save/update", function (data) {
        if(data.resultCode==0){
        	Feng.success("修改成功!");
            if(window.parent.MgrUser != undefined){
                window.parent.MgrUser.table.refresh();
                UserInfoDlg.close();
            }
    	}else{
    		Feng.error(data.msg + "!");
    	}
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.userInfoData);
    ajax.start();
};

/**
 * 修改密码
 */
UserInfoDlg.chPwd = function () {
	var rePwd = $("#rePwd").val();
	var newPwd = $("#newPwd").val();
	if(rePwd!=newPwd){
		Feng.error("添加失败!" + data.responseJSON.message + "!");
	}
    var ajax = new $ax(Feng.ctxPath + "/sys/sysUser/save/user_chpwd", function (data) {
        if(data.resultCode==0){
        	Feng.success("修改成功!");
    	}else{
    		Feng.error(data.msg + "!");
    	}
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set("oldPwd");
    ajax.set("newPwd");
    ajax.set("rePwd");
    ajax.start();

};

/**
 * 请求角色数据
 */
UserInfoDlg.getRoleData = function () {
    var ajax = new $ax(Feng.ctxPath + "/sys/sysUser/getRoleData", function (data) {
    	var rid = $('#roleId option:selected').val();
        for (var i = 0; i < data.length; i++) {
        	if (!(rid == data[i].id)) {
        		$("#roleId").append('<option value='+data[i].id+'>'+data[i].name+'</option>');
        	}
		}
    }, function (data) {
        console.error("请求角色数据失败!" + data.responseJSON.message + "!");
    });
    ajax.start();
};

/*function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(
            event.target).parents("#menuContent").length > 0)) {
        UserInfoDlg.hideDeptSelectTree();
    }
}*/

UserInfoDlg.showOfficeSelectTree = function() {
    var pName = $("#parentName");
    var pNameOffset = $("#parentName").offset();
    $("#parentOfficeMenu").css({
        left : pNameOffset.left + "px",
        top : pNameOffset.top + pName.outerHeight() + "px"
    }).slideDown("fast");

    $("body").bind("mousedown", onBodyDown);
}

UserInfoDlg.onClickOffice = function(e, treeId, treeNode) {
    console.log(treeNode.id)
    $("#parentName").attr("value", UserInfoDlg.zTreeInstance.getSelectedVal());
    $("#officeId").attr("value", treeNode.id);
    //选择机构后，隐藏树
    UserInfoDlg.hideOfficeSelectTree();
}

UserInfoDlg.hideOfficeSelectTree = function() {
    $("#parentOfficeMenu").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);// mousedown当鼠标按下就可以触发，不用弹起
}

function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "parentOfficeMenu" || $(
            event.target).parents("#parentOfficeMenu").length > 0)) {
        UserInfoDlg.hideOfficeSelectTree();
    }
}

UserInfoDlg.selectFile = function () {
	//触发选择文件的按钮
	$("#fileUploadBtn").click();
}

UserInfoDlg.uploadFile = function () {
	//触发选择文件的按钮
	var fileObj = document.getElementById("fileUploadBtn").files[0]; // js 获取文件对象
    if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
        alert("请选择图片");
        return;
    }
    var formFile = new FormData();
    formFile.append("file", fileObj); //加入文件对象
    var data = formFile;
    $.ajax({
        url: "/sys/sysUser/upload",
        data: data,
        type: "post",
        dataType: "json",
        cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false, //必须
        success: function (data) {
       	 if(data.resultCode==1){
        	Feng.success("上传成功!");
        	var url = data.data;
        	$("#avatarPreId").attr("src",url);
        	$("#avatar").val(url);
       	 }else{
        		Feng.error(data.msg + "!");
        	}
        },
        error:function(err){
       	 console.log(err);
        }
    })
}


$(function () {
    /*var ztree = new $ZTree("treeDemo", "/sys/sysDept/tree");
    ztree.bindOnClick(UserInfoDlg.onClickDept);
    ztree.init();
    instance = ztree;*/

    var ztree = new $ZTree("parentOfficeMenuTree", "/sys/sysOffice/tree/-1");
    ztree.bindOnClick(UserInfoDlg.onClickOffice);
    ztree.init();
    UserInfoDlg.zTreeInstance = ztree;


    // 请求角色数据
    UserInfoDlg.getRoleData();
    //初始化性别选项
    $("#sex").val($("#sexValue").val());

    // 初始化头像上传
    //var avatarUp = new $WebUpload("avatar");
    //avatarUp.init();
});
